//
//  PopoverAnimator.m
//  Weibo
//
//  Created by student on 16/4/26.
//  Copyright © 2016年 Mcc. All rights reserved.
//

#import "PopoverAnimator.h"
#import "PopoverPresentationController.h"

@interface PopoverAnimator()
{
    BOOL isPresent;//判断是否弹出
}
@end


@implementation PopoverAnimator

#pragma mark - UIViewControllerTransitioningDelegate
//告诉系统谁来负责转场动画
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    PopoverPresentationController *pc=[[PopoverPresentationController alloc]initWithPresentedViewController:presented presentingViewController:presenting];
    pc.presentFrame=self.presentFrame;
    return pc;
}
//谁来负责人弹出动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    isPresent=YES;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kNontificationPopoverWillShow object:nil userInfo:nil];
    return self;
}

//谁来负责消失动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    isPresent=NO;
    [[NSNotificationCenter defaultCenter]postNotificationName:kNontificationPopoverWillDismiss object:nil userInfo:nil];
    return self;
}
#pragma mark - 动画效果
//动画时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 1;
}
// 具体动画怎么进行
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    if(isPresent)
    {
        //1.拿到要展现的视图
        UIView *toView=[transitionContext viewForKey:UITransitionContextToViewKey];
//        toView.transform=CGAffineTransformMakeScale(1.0, 0.0);
//        toView.layer.anchorPoint=CGPointMake(0, 0);//锚点
        toView.alpha=0;
        
        //将要展现的视图添加到容器上
        [[transitionContext containerView] addSubview:toView];
        
        //2.执行动画
        [UIView animateWithDuration:0.5 animations:^{
            //重置
//            toView.transform=CGAffineTransformIdentity;
            toView.alpha=1;
        }completion:^(BOOL finished) {
            //得告诉系统执行完了
            [transitionContext completeTransition:YES];
        }];
    }
    else
    {
        //关闭
        UIView *fromView=[transitionContext viewForKey:UITransitionContextFromViewKey];
        fromView.transform=CGAffineTransformIdentity;
        [UIView animateWithDuration:0.5 animations:^{
            //            fromView.transform=CGAffineTransformMakeScale(1.0, 0.00001);
            fromView.alpha=0;
        }completion:^(BOOL finished) {
            //得告诉系统执行完了
            [transitionContext completeTransition:YES];
        }];
    }
    
}
@end
